package common

import (
	"github.com/go-xorm/xorm"
	"../model"
	_ "github.com/go-sql-driver/mysql" //下划线是只运行包里面的init函数
	"strconv"
)

var DbEngin *xorm.Engine
//init函数在main函数运行之前运行
func InitMysql() (err error) {

	drivername := "mysql"
	//mysql
	DsName := G_config.MysqlUserName + ":" + G_config.MysqlPassword + "@" + "(" + G_config.MysqlIp + ":" + G_config.MysqlPort + ")/" + G_config.MysqlDatabase + "?charset=" + G_config.MysqlCharset

	DbEngin, err = xorm.NewEngine(drivername, DsName)
	if err != nil && err.Error() != "" {
		G_logger.Fatal(err.Error())
	}
	//测试数据库是否可以连通
	err = DbEngin.Ping()
	if err != nil {
		G_logger.Fatal("数据库连接失败")
	} else {
		G_logger.Info("数据库连接成功")
	}

	//是否显示sql语句
	bool, err := strconv.ParseBool(G_config.MysqlShowSql)
	if err != nil {
		G_logger.Fatal(err.Error())
	}
	DbEngin.ShowSQL(bool)

	//设置数据库最大打开的连接数
	num, err := strconv.Atoi(G_config.MysqlConn)
	DbEngin.SetMaxOpenConns(num)

	//自动建表
	DbEngin.Sync2(new(model.User), new(model.Contact), new(model.Community))

	return
}
